<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>茶叶溯源系统</h2>
        <p>基于区块链的茶叶品质溯源平台</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="email">
          <el-input
            v-model="loginForm.email"
            type="email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
            size="large"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe">
              记住我
            </el-checkbox>
            <el-link type="primary" @click="goToForgotPassword">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-btn"
          >
            登录
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="register-link">
            <span>还没有账户？</span>
            <el-link type="primary" @click="goToRegister">
              立即注册
            </el-link>
          </div>
        </el-form-item>
      </el-form>

      <!-- 角色说明 -->
      <div class="role-info">
        <el-collapse accordion>
          <el-collapse-item title="用户角色说明" name="roles">
            <div class="role-list">
              <div class="role-item">
                <strong>茶农 (Farmer)</strong>
                <p>负责茶叶的种植、采摘和初加工，创建和管理茶叶批次</p>
              </div>
              <div class="role-item">
                <strong>物流方 (Logistics)</strong>
                <p>负责茶叶运输过程的记录和管理</p>
              </div>
              <div class="role-item">
                <strong>商家 (Merchant)</strong>
                <p>负责茶叶的销售和最终消费记录</p>
              </div>
              <div class="role-item">
                <strong>消费者 (Consumer)</strong>
                <p>可以查询茶叶的完整溯源信息</p>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <!-- 公开溯源查询入口 -->
    <div class="trace-entry">
      <el-card class="trace-card">
        <div class="trace-header">
          <el-icon><Search /></el-icon>
          <h3>茶叶溯源查询</h3>
        </div>
        <p>输入茶叶批次ID，免登录查看完整溯源信息</p>
        <el-input
          v-model="traceId"
          placeholder="请输入批次ID"
          size="large"
          class="trace-input"
        >
          <template #append>
            <el-button type="primary" @click="handleTrace" :loading="tracing">
              查询
            </el-button>
          </template>
        </el-input>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref(null)

// 登录表单
const loginForm = reactive({
  email: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 状态
const loading = ref(false)
const traceId = ref('')
const tracing = ref(false)

// 方法
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    
    loading.value = true
    const result = await authStore.login(loginForm)
    
    if (result.success) {
      ElMessage.success('登录成功')
      router.push('/dashboard')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    if (error !== false) {  // 排除表单验证失败
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}

const goToForgotPassword = () => {
  ElMessage.info('忘记密码功能开发中')
}

const handleTrace = () => {
  if (!traceId.value.trim()) {
    ElMessage.warning('请输入批次ID')
    return
  }
  
  router.push(`/trace/${traceId.value.trim()}`)
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  gap: 40px;
}

.login-card {
  width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.register-link {
  text-align: center;
  width: 100%;
}

.register-link span {
  color: #7f8c8d;
  margin-right: 8px;
}

.role-info {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.role-list {
  padding: 0 8px;
}

.role-item {
  margin-bottom: 16px;
}

.role-item:last-child {
  margin-bottom: 0;
}

.role-item strong {
  color: #2c3e50;
  display: block;
  margin-bottom: 4px;
}

.role-item p {
  color: #7f8c8d;
  font-size: 13px;
  line-height: 1.4;
  margin: 0;
}

.trace-entry {
  width: 400px;
}

.trace-card {
  text-align: center;
}

.trace-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 12px;
}

.trace-header h3 {
  color: #2c3e50;
  margin: 0;
  font-size: 18px;
}

.trace-header .el-icon {
  font-size: 20px;
  color: #409eff;
}

.trace-card p {
  color: #7f8c8d;
  margin-bottom: 20px;
  font-size: 14px;
}

.trace-input {
  width: 100%;
}

/* 响应式 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    gap: 20px;
    padding: 16px;
  }
  
  .login-card,
  .trace-entry {
    width: 100%;
    max-width: 400px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
}
</style>